/**
 * 换头像
 */
import React, { Component } from 'react';
import { Button, message, Upload, Icon, Input } from 'antd';
import { getUrlParams } from 'yl-util';
import { api } from '../../constants';
import { fetch } from '../../utils';

let openId = '';
const urlParams = getUrlParams(window.location.href.split('?')[1]);
if (urlParams && urlParams.id) {
  openId = window.btoa(window.btoa(`${urlParams.id}yqcmxssLcJL1l8jnlC`));
}

export default class Badge extends Component {
  state = {
    fileList: [],
    uploading: false,
    disabled: false,
    userInfo: {},
  };

  componentDidMount() {
    this.getUserInfo();
  }

  // 获取用户信息
  async getUserInfo() {
    const params = {
      openId,
    };
    const response = await fetch(`${api.userInfo}`, {
      method: 'POST',
      body: params,
    });
    if (response.msgCode === 'S0000') {
      if (response.data.user.mid === 78 || response.data.user.mid === 0) {
        this.setState({ isCrystal: true });
      }
      this.setState({ userInfo: response.data.user });
    }
  }

  handleUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    if (fileList[0]) {
      formData.append('headImg', fileList[0]);
    }
    formData.append('openId', openId);
    formData.append('version', 'v1');
    // formData.append('change_head_count', 0);
    fetch(api.uploadheadimg, {
      method: 'POST',
      noHeader: true,
      body: formData,
    }).then(response => {
      if (response.msgCode === 'S0000') {
        this.setState({ disabled: true });
        this.getUserInfo();
        message.success('头像修改成功');
      } else {
        message.error(response.message || '出错了');
      }
    });
  }

  async changeNickname(value) {
    const valueWithoutSpace = value.replace(/\s/g, '').replace(/(,|，)/g, ',');
    const params = {
      openId,
      nickName: valueWithoutSpace,
    };
    const response = await fetch(`${api.changenickhead}`, {
      method: 'POST',
      body: params,
    });
    this.getUserInfo();
    if (response.msgCode === 'S0000') {
      message.success(response.data ? response.data.msg : '修改成功');
    } else {
      message.info(response.message);
    }
  }

  render() {
    const { uploading, fileList, disabled, userInfo } = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };

    return (
      <div>
        <p />
        <h3>当前鲜花：{userInfo.flower}</h3>
        <p>
          {/* 修改头像次数：{userInfo.changeHeadCount} */}
          修改头像次数：{userInfo.changeHeadCount} 修改昵称次数：{userInfo.changeNickCount}
        </p>
        <p>
          注：修改头像次数为 1 的话如果再次更换头像会扣<span style={{ color: 'red' }}>50万</span>花花！
        </p>
        <p>
          注：修改昵称次数为 1 的话如果再次更换昵称会扣<span style={{ color: 'red' }}>100万</span>花花！
        </p>
        <Upload {...props}>
          <Button>
            <Icon type="upload" /> 选择图片
          </Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0 || disabled}
          loading={uploading}
          style={{ marginTop: 16 }}
        >
          {uploading ? '上传中' : '更换头像'}
        </Button>
        <p />
        <p />
        <p>
          <Input.Search
            className="bless-search"
            placeholder="输入要修改的昵称"
            enterButton="修改昵称"
            onSearch={this.changeNickname.bind(this)}
          />
        </p>
      </div>
    );
  }
}
